const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const myToastNone = (msg, time=600) => {
  wx.showToast({title: msg, icon: 'none'})
  setTimeout(() => {wx.hideToast()}, time)
}

const myToastSuccess = (msg, time=600) => {
  wx.showToast({title: msg, icon: 'success'})
  setTimeout(() => {wx.hideToast()}, time)
}

const myToastError = (msg, time=600) => {
  wx.showToast({title: msg, icon: 'error'})
  setTimeout(() => {wx.hideToast()}, time)
}

const myLoading = (msg='加载中...', time=600) => {
  wx.showLoading({title: msg})
  setTimeout(() => {wx.hideLoading()}, time)
}

const checkIfLogin = ()=>{
    const userInfo = wx.getStorageSync('userInfo')
    if(!userInfo) {
        myToastError('请先登录～')
        return false
    }
    return userInfo
}
const app = getApp() // 获取全局APP对象
// 获取当前地理位置
const getLocation = ()=>{
    let currentLocation = ''
    wx.getLocation({ // 获取当前位置
        type: 'gcj02' // gcj02火星坐标系，用于地图标记点位
    }).then(async res => { // 获取成功
        const {
            latitude,
            longitude
        } = res // 如果传入为空，则使用data内数据
        console.log("经纬度：" + longitude + ", " + latitude)
        // wx.setStorageSync('currentLongitudeAndLatitude', [longitude, latitude])
        await app.call({ // 发起云函数请求
            name: 'location', // 业务为location，获取经纬度信息
            data: { // 传入经纬度信息
                location: `${latitude},${longitude}`
            },
            load: false // 不显示加载loading，静默执行
        }).then(res => {
            // this.setData({
            //     keyword: res.adinfo.split(',')[2] + res.adinfo.split(',')[3]
            // })
            currentLocation = res.adinfo.split(',')[3]
            // console.log('当前地理区位,', currentLocation)
        })
    }).catch(e => {
        // 获取失败
        wx.showToast({
            title: '获取当前定位失败',
            icon: 'none'
        })
        setTimeout(() => {
            wx.hideToast()
        }, 800)
    })
    return currentLocation
}

import GoEasy from '../static/lib/goeasy-2.4.7.min'
const connectToGoEasy = ()=> {
    // 初始化goEasy
    wx.goEasy = GoEasy.getInstance({
        host:'hangzhou.goeasy.io',//应用所在的区域地址
        appkey: 'BC-b9f81c3b05684372ac10c9a5a78a8194',// common key
        modules:['im']
    });
    wx.GoEasy = GoEasy;
    // 连接goeasy
    let currentUser = wx.getStorageSync('userInfo')
    if(!currentUser){
        return
    }
    if (wx.goEasy.getConnectionStatus() === 'disconnected') {
        wx.goEasy.connect({
            id: currentUser.userOpenId,
            data: {
                name: currentUser.nickName,
                avatar: currentUser.avatarUrl
            },
            onSuccess: () => {
                console.log('GoEasy connect successfully.')
            },
            onFailed: (error) => {
                console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
            },
            onProgress: (attempts) => {
                console.log('GoEasy is connecting', attempts);
            }
        });
    }
}

const disconnectToGoEasy = ()=>{
    //断开连接
    wx.goEasy.disconnect({
        onSuccess: function(){
            console.log("GoEasy disconnect successfully.")
        },
        onFailed: function(error){
            console.log("Failed to disconnect GoEasy, code:" + error.code + ",error:" + error.content);
        }
    });
}

// 发送消息
const sendMessage = (text, toUserOpenId, toUserName, toUserAvatar)=>{
    // console.log(text, toUserOpenId, toUserName, toUserAvatar)
    // 发送文本与表情
    let textMessage = wx.goEasy.im.createTextMessage({
        text: text,
        to: {
            id: toUserOpenId,
            type: wx.GoEasy.IM_SCENE.PRIVATE,
            data: {
                name: toUserName,
                avatar: toUserAvatar
            }
        }
    })
    wx.goEasy.im.sendMessage({
        message: textMessage,
        onSuccess: function (message) {
            console.log('发送成功.', message);
        },
        onFailed: function (error) {
                console.log('发送失败:', error);
        }
    })
}

// 消息提示音
const playBeep = ()=>{
    const answerRightAudio = wx.createInnerAudioContext();
    answerRightAudio.autoplay = false;
    answerRightAudio.src = 'https://776f-work1-0g1b3grp436e9236-1311803114.tcb.qcloud.la/music/iphone.wav?sign=688f8ae517a6b28cd38c3d0af598e883&t=1656216231'
    answerRightAudio.play()
}

module.exports = {
  formatTime: formatTime,
  myToastNone: myToastNone,
  myToastSuccess: myToastSuccess,
  myToastError: myToastError,
  myLoading: myLoading,
  checkIfLogin: checkIfLogin,
  getLocation: getLocation,
  connectToGoEasy: connectToGoEasy,
  disconnectToGoEasy: disconnectToGoEasy,
  sendMessage: sendMessage,
  playBeep: playBeep
}
